<template>
    <div class="cart-tip">
        <p>{{ message }}</p>
        <p v-if="countdown">{{ countdown }}</p>
        <button v-if="showButton" @click="cancel">取消</button>
    </div>
</template>
  
<script>
export default {
    props: {
        message: String,
        duration: {
            type: Number,
            default: 2000
        },
        onConfirm: Function,
        onCancel: Function
    },
    data() {
        return {
            countdown: '',
            showButton: false,
            timer: null
        }
    },
    methods: {
        startCountdown() {
            let count = this.duration / 1000;
            this.countdown = `${count} 秒后自动前往购物车`;
            this.timer = setInterval(() => {
                count--;
                if (count <= 0) {
                    clearInterval(this.timer);
                    this.timer = null;
                    this.countdown = '';
                    this.showButton = false;
                    if (typeof this.onConfirm === 'function') {
                        this.onConfirm();
                    }
                } else {
                    this.countdown = `${count} 秒后自动前往购物车`;
                }
            }, 1000);
        },
        cancel() {
            clearInterval(this.timer);
            this.countdown = '';
            this.showButton = false;
            if (typeof this.onCancel === 'function') {
                this.onCancel();
            }
        }
    },
    mounted() {
        this.startCountdown();
        this.showButton = true;
    },
    beforeUnmount() {
        clearInterval(this.timer);
    }
}
</script>
<style>
.cart-tip{
    width: 300px;
    height: 300px;
    background-color: #fff;
    text-align: center;
}
</style>
  